1 /**
2 * Copyright 2014 Netflix, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package rx.internal.operators;
17
18 import rx.Observable.Operator;
19 import rx.Subscriber;
20 import rx.exceptions.OnErrorThrowable;
21 import rx.functions.Func1;
22
23 /**
24 * Filters an Observable by discarding any items it emits that do not meet some test.
25 * <p>
26 * <img width="640" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/filter.png" alt="">
27 */
28 public final class OperatorFilter<T> implements Operator<T, T> {
29
30 private final Func1<? super T, Boolean> predicate;
31
32 public OperatorFilter(Func1<? super T, Boolean> predicate) {
33 this.predicate = predicate;
34 }
35
36 @Override
37 public Subscriber<? super T> call(final Subscriber<? super T> child) {
38 return new Subscriber<T>(child) {
39
40 @Override
41 public void onCompleted() {
42 child.onCompleted();
43 }
44
45 @Override
46 public void onError(Throwable e) {
47 child.onError(e);
48 }
49
50 @Override
51 public void onNext(T t) {
52 try {
53 if (predicate.call(t)) {
54 child.onNext(t);
55 } else {
56 // TODO consider a more complicated version that batches these
57 request(1);
58 }
59 } catch (Throwable e) {
60 child.onError(OnErrorThrowable.addValueAsLastCause(e, t));
61 }
62 }
63
64 };
65 }
66
67 }